package com.mark.web.stars.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mark.common.Constant;
import com.mark.common.ServerResponse;
import com.mark.common.exception.Campuso2oException;
import com.mark.common.utils.PropertiesUtil;
import com.mark.web.common.entity.SelectVo;
import com.mark.web.stars.entity.po.Fragment;
import com.mark.web.stars.entity.vo.FragmentVo;
import com.mark.web.stars.mapper.FragmentMapper;
import com.mark.web.stars.service.IFragmentService;
import com.mark.web.sys.entity.po.Dict;
import com.mark.web.sys.entity.po.User;
import com.mark.web.sys.mapper.DictMapper;
import com.mark.web.sys.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 碎片的service层接口测试
 * @Author: Mark
 * @CreateDate: 2019/6/2 17:55
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Service
public class FragmentServiceImpl implements IFragmentService {

    private final FragmentMapper fragmentMapper;
    private final UserMapper userMapper;
    private final DictMapper dictMapper;

    @Autowired
    public FragmentServiceImpl(FragmentMapper fragmentMapper, UserMapper userMapper, DictMapper dictMapper) {
        this.fragmentMapper = fragmentMapper;
        this.userMapper = userMapper;
        this.dictMapper = dictMapper;
    }

    @Override
    public ServerResponse<String> add(Fragment fragment) {
        //碎片的参数校验
        Integer fkTypeId = fragment.getFkTypeId();
        if(fkTypeId == null){
            throw new Campuso2oException("请选择碎片类型！");
        }
        if(StringUtils.isBlank(fragment.getContent())){
            throw new Campuso2oException("碎片内容不能为空！");
        }
        if(fragment.getContent().length() > 140){
            throw new Campuso2oException("碎片内容的字符个数不能大于140！");
        }

        // TODO: 2019/6/9 查询字典信息放入缓存
        List<Dict> dictList = dictMapper.selectByParentId(Constant.CampusProperties.FRAGMENT_TYPE_ID);
        List<Integer> dictFragmentTypeIdList = dictList.stream().map(Dict::getId).collect(Collectors.toList());
        if(!dictFragmentTypeIdList.contains(fkTypeId)){
            throw new Campuso2oException("输入的碎片类型id有误！");
        }

        //默认值
        if(StringUtils.isBlank(fragment.getImgAddress())){
            fragment.setImgAddress(StringUtils.EMPTY);
        }
        fragment.setLiked(0);

        int insert = fragmentMapper.insert(fragment);
        if(insert != Constant.SUCCESS){
            return ServerResponse.createByErrorMessage("新增碎片失败！");
        }
        return ServerResponse.createBySuccessMessage("添加碎片成功！");
    }

    @Override
    public ServerResponse<PageInfo<FragmentVo>> getFragmentList(Map<String, Object> requestMap) {
        //取出请求中的参数
        int pageNum = (int) requestMap.get("pageNum");
        int pageSize = (int) requestMap.get("pageSize");
        int currentUserId = (int) requestMap.get("currentUserId");
        Integer fkTypeId = (Integer) requestMap.get("fkTypeId");

        //构建查询BD的参数
        Map<String, Object>  paramMap  = Maps.newHashMap();
        paramMap.put("currentUserId",currentUserId);
        paramMap.put("fkTypeId",fkTypeId);
        PageHelper.startPage(pageNum, pageSize);
        List<Fragment> fragmentList = fragmentMapper.selectFragmentByCondition(paramMap);

        //构建响应VO信息
        List<FragmentVo> fragmentVoList = Lists.newArrayList();
        fragmentList.forEach(fragment -> {
            Integer fkUserId = fragment.getFkUserId();
            User user = userMapper.selectByPrimaryKey(fkUserId);
            fragmentVoList.add(new FragmentVo(fragment,user));
        });
        PageInfo<FragmentVo> result = new PageInfo<>(fragmentVoList);
        result.setTotal(new PageInfo<>(fragmentList).getTotal());
        return ServerResponse.createBySuccess(result);
    }

    @Override
    public List<Map<String, Object>> getTypeInfo() {
        List<Map<String, Object>> fragmentTypeList = fragmentMapper.selectFragmentType();
        fragmentTypeList.forEach(map->{
            Number fkTypeId  = (Number) map.get("fkTypeId");
            Dict fragmentType = dictMapper.selectByPrimaryKey(fkTypeId.intValue());
            //标签类型名称
            String typeName = fragmentType.getName();
            //标签类型图片资源
            String url = fragmentType.getDescription();
            map.put("typeName", typeName);
            map.put("url",  Constant.IMAGE_HOST+url);
        });

        //将热门标签置顶
        List<Map<String, Object>> result = Lists.newArrayList();
        fragmentTypeList.forEach(map->{
            Number fkTypeId  = (Number) map.get("fkTypeId");
            if(fkTypeId.intValue() == (Constant.CampusProperties.HOST_DICT_ID)){
                result.add(map);
            }
        });
        fragmentTypeList.forEach(map->{
            Number fkTypeId  = (Number) map.get("fkTypeId");
            if(fkTypeId.intValue() != (Constant.CampusProperties.HOST_DICT_ID)){
                result.add(map);
            }
        });
        return result.stream().limit(12).collect(Collectors.toList());
    }

    @Override
    public List<SelectVo<String, Integer>> getTypeSelect() {
        List<Dict> dictList = dictMapper.selectByParentId(Constant.CampusProperties.FRAGMENT_TYPE_ID);
        return dictList
                .stream()
                //过滤掉“热门”标签
                .filter(dict -> !dict.getId().equals(Constant.CampusProperties.HOST_DICT_ID))
                .map(dict -> new SelectVo<>(dict.getName(), dict.getId()))
                .collect(Collectors.toList());
    }

}
